﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using QQ2564874169.Core.Encryption;

namespace QQ2564874169.Aliyun.ShortMessage
{
    public class SendSMS: SysParam
    {
        public string Action { get; }
        public string Version { get; }
        public string RegionId { get; set; }
        public List<string> PhoneNumbers { get; }
        public string SignName { get; set; }
        public string TemplateCode { get; set; }
        public string TemplateParam { get; set; }
        public string OutId { get; set; }
        public bool IsGetRequest { get; set; }

        public SendSMS()
        {
            Action = "SendSms";
            Version = "2017-05-25";
            PhoneNumbers = new List<string>();
        }

        private string GetSignature()
        {
            var dict = new SortedDictionary<string, string>(StringComparer.Ordinal);
            
            var ps = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (var p in ps)
            {
                if (p.Name == nameof(IsGetRequest) || p.Name == nameof(AccessSecret))
                    continue;
                var v = p.GetValue(this);
                if (v == null)
                    continue;
                if (p.Name == nameof(PhoneNumbers))
                    v = string.Join(",", (List<string>) v);
                dict.Add(p.Name, UrlEncode(v.ToString()));
            }
            var qs = string.Join("&", dict.Keys.Select(k => UrlEncode(k) + "=" + dict[k]));
            var signstr = (IsGetRequest ? "GET" : "POST") + "&" + UrlEncode("/") + "&" + UrlEncode(qs);
            signstr = Encrypt.HmacSHA1(signstr, AccessSecret + "&", Encoding.UTF8);
            return UrlEncode(signstr);
        }
    }
}
